﻿using System;
using System.Windows.Forms;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win;
using Litografia.BusinessEntities;
using Litografia.BusinessComponents;
using Nortec.Security;

namespace Litografia.UI.Mantenimientos
{
    public partial class MantMaquinasForm : BaseForm
    {
        public MantMaquinasForm()
        {
            InitializeComponent();
        }

        #region Declarations
        BEMaquina.MaquinaDataTable machines;
        BEMaquina.MaquinaRow selectedMachine;
        #endregion

        #region Event Handlers
        private void MantMaquinasForm_Load(object sender, EventArgs e)
        {
            ConfigureToolBar(toolStrip, ToolBarButtons.Save |
                                        ToolBarButtons.New |
                                        ToolBarButtons.Delete |
                                        ToolBarButtons.Close);
            LoadMachinesGrid(true);
            ConfigureMachinesGrid();
            toolStrip.ItemClicked += ToolStripItemClicked;
            ToggleButton(toolStrip, ToolBarButtons.Delete, false);
        }
        private void ToolStripItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch ((ToolBarButtons)e.ClickedItem.Tag)
            {
                case ToolBarButtons.Save:
                    Save();
                    break;
                case ToolBarButtons.Delete:
                    Delete();
                    break;
                case ToolBarButtons.New:
                    ClearControls(Controls);
                    txtNombre.Focus();
                    ToggleButton(toolStrip, ToolBarButtons.Delete, false);
                    machinesGrid.Selected.Rows.Clear();
                    machinesGrid.Refresh();
                    break;
                case ToolBarButtons.Close:
                    Close();
                    break;
            }
        }
        private void machinesGrid_AfterSelectChange(object sender, AfterSelectChangeEventArgs e)
        {
            if (machinesGrid.Selected.Rows.Count > 0)
            {
                if (machinesGrid.Selected.Rows[0].IsDataRow)
                {
                    var selectedId = (int)machinesGrid.Selected.Rows[0].Cells[machines.IdColumn.Ordinal].Value;
                    selectedMachine = machines.FindById(selectedId);
                    UnPack(selectedMachine);
                    ToggleButton(toolStrip, ToolBarButtons.Delete, true);
                }
                else machinesGrid.Selected.Rows.Clear();
            }
            else
            {
                selectedMachine = null;
                ClearControls(Controls);
                ToggleButton(toolStrip, ToolBarButtons.Delete, false);
            }
        }
        #endregion

        #region Methods: Private
        private void LoadMachinesGrid(bool sort)
        {
            machines = BCMaquina.Get(NortecMembership.CompanyId);
            machinesGrid.DataSource = machines;

            if (sort)
            {
                machinesGrid.DisplayLayout.Bands[0].SortedColumns.Clear();
                machinesGrid.DisplayLayout.Bands[0].SortedColumns.Add(machinesGrid.DisplayLayout.Bands[0].Columns[machines.NombreColumn.Ordinal], false);
            }

            if (machinesGrid.Rows.Count > 0)
            {
                machinesGrid.ActiveRow = machinesGrid.Rows[0];
               // machinesGrid.Selected.Rows.Add(machinesGrid.Rows[0]);
            }
            else
            {
                selectedMachine = null;
                ToggleButton(toolStrip, ToolBarButtons.Delete, false);
            }

            
        }
        private void ConfigureMachinesGrid()
        {

            // Oculta algunas columnas 
            machinesGrid.DisplayLayout.Bands[0].Columns[machines.EmpresaIdColumn.Ordinal].Hidden = true;
            machinesGrid.DisplayLayout.Bands[0].Columns[machines.IdColumn.Ordinal].Hidden = true;

            // Alineamientos
            foreach (UltraGridColumn col in machinesGrid.DisplayLayout.Bands[0].Columns)
                col.Header.Appearance.TextHAlign = HAlign.Center;
            machinesGrid.DisplayLayout.Bands[0].Columns[machines.CostoxHoraColumn.Ordinal].CellAppearance.TextHAlign = HAlign.Right;

            // Ancho de columnas
            machinesGrid.DisplayLayout.Bands[0].Columns[machines.NombreColumn.Ordinal].Width = 375;
            machinesGrid.DisplayLayout.Bands[0].Columns[machines.CostoxHoraColumn.Ordinal].Width = 100;

            // Formato de despliege
            machinesGrid.DisplayLayout.Bands[0].Columns[machines.CostoxHoraColumn.Ordinal].Format = "#,##0.00";

            // Filters
            machinesGrid.DisplayLayout.Bands[0].Columns[machines.NombreColumn.Ordinal].AllowRowFiltering = DefaultableBoolean.False;
            machinesGrid.DisplayLayout.Bands[0].Columns[machines.CostoxHoraColumn.Ordinal].AllowRowFiltering = DefaultableBoolean.False;
            machinesGrid.DisplayLayout.Bands[0].Columns[machines.NombreColumn.Ordinal].Header.Caption = "Nombre";
            machinesGrid.DisplayLayout.Bands[0].Columns[machines.CostoxHoraColumn.Ordinal].Header.Caption = "Costo x Hora";

            machinesGrid.DisplayLayout.Bands[0].Override.CellClickAction = CellClickAction.RowSelect;

        }
        private void UnPack(BEMaquina.MaquinaRow machine)
        {
            txtNombre.Text = machine.Nombre;
            txtCosto.Text = machine.CostoxHora.ToString();
        }
        private void Save()
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                if (ValidateEntries())
                {
                    var row = Pack();
                    if (selectedMachine == null)
                        BCMaquina.Add(row);
                    else
                        BCMaquina.Update(row);
                    ClearControls(Controls);
                    LoadMachinesGrid(false);
                }
            }
            catch (Exception ex)
            {
                DisplayError("No se pudo guardar la información.", ex);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
        private bool ValidateEntries()
        {
            var functionReturnValue = false;
            var msg = "";
            decimal costo;

            if (string.IsNullOrEmpty(txtNombre.Text))
            {
                msg = "Debe ingresar el nombre de la máquina";
                txtNombre.Focus();
            }
            else if (!Decimal.TryParse(txtCosto.Text, out costo) || costo <= 0)
            {
                msg = "El costo por hora ingresado no es válido";
                txtCosto.Focus();
            }
            else
                functionReturnValue = true;

            if (!functionReturnValue)
                MessageBox.Show(msg, Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            return functionReturnValue;
        }
        private BEMaquina.MaquinaRow Pack()
        {
            var machine = (new BEMaquina.MaquinaDataTable()).NewMaquinaRow();

            if (selectedMachine != null)
                machine.Id = selectedMachine.Id;
            machine.EmpresaId = NortecMembership.CompanyId;
            machine.Nombre = txtNombre.Text.Trim();
            machine.CostoxHora = Convert.ToDecimal(txtCosto.Text);
            
            return machine;
        }
        private void Delete()
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                if (selectedMachine == null)
                    MessageBox.Show("Debe seleccionar una máquina antes de eliminarla.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                else
                {
                    if (MessageBox.Show("¿Está seguro de eliminar la máquina \"" + selectedMachine.Nombre+ "\"?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        BCMaquina.Delete(selectedMachine.Id);
                        ClearControls(Controls);
                        LoadMachinesGrid(false);
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayError("No se pudo eliminar la información de la máquina.", ex);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
        #endregion

    }
}
